package com.lagou.filter;

import com.lagou.controller.ValidateCodeController;
import com.lagou.exception.ValidateCodeException;
import com.lagou.service.impl.MyAuthenticationServiceImpl;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author junbao
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MyAuthenticationServiceImpl myAuthenticationService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        // 判断是否是登陆请求
        if(httpServletRequest.getRequestURI().equals("/login") && httpServletRequest.getMethod().equalsIgnoreCase("post")) {
            String imageCode = httpServletRequest.getParameter("imageCode");
            System.out.println(imageCode);
            try{
                validate(httpServletRequest, imageCode);
            }catch (ValidateCodeException e) {
                myAuthenticationService.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }

        // 如果不是登陆请求
        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }

    private void validate(HttpServletRequest httpServletRequest, String imageCode) {
        // 从redis中获取验证码
        String redisKey = ValidateCodeController.REDIS_KEY_IMAGE_CODE + "-" + httpServletRequest.getRemoteAddr();
        String redisImageCode = stringRedisTemplate.boundValueOps(redisKey).get();
        // 验证码判断
        if(!StringUtils.hasText(imageCode)) {
            throw new ValidateCodeException("imageCode can not blank");
        }
        if(redisImageCode == null) {
            throw new ValidateCodeException("imageCode is expire");
        }
        if(!redisImageCode.equals(imageCode)) {
            throw new ValidateCodeException("imageCode is not right");
        }
        // 从redis中删除验证码
        stringRedisTemplate.delete(redisKey);
    }
}
